package com.shuhua.taskServer.controller;

import com.shuhua.pojo.entity.TaskHandle;
import com.shuhua.taskServer.service.TaskHandleService;
import com.shuhua.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;

@RestController
@RequestMapping("/taskHandle")
public class TaskHandleController {
    @Autowired
    private TaskHandleService taskHandleService;

    private static final String[] TASKHANDLE_FIELDS = {"handleid", "taskid", "craftsmanid", "handletime", "detail"};
    private static final String[] RESOURCE_FIELDS = {"resourcesid", "handleid", "fileurl", "createdat"};

    @PostMapping
    public Result<?> add(@RequestBody TaskHandle taskHandle) {
        taskHandleService.save(taskHandle);
        return Result.success();
    }

    @DeleteMapping("/{handleId}")
    public Result<?> delete(@PathVariable Long handleId) {
        taskHandleService.removeById(handleId);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody TaskHandle taskHandle) {
        taskHandleService.updateById(taskHandle);
        return Result.success();
    }

    @GetMapping("/{handleId}")
    public Result<TaskHandle> get(@PathVariable Long handleId) {
        TaskHandle handle = taskHandleService.getById(handleId);
        return Result.success(handle);
    }

    @GetMapping("/list")
    public Result<List<Map<String, Object>>> list() {
        List<Map<String, Object>> flatList = taskHandleService.listHandleWithResources();
        java.util.Map<Long, java.util.LinkedHashMap<String, Object>> grouped = new java.util.LinkedHashMap<>();
        for (Map<String, Object> row : flatList) {
            Long handleId = row.get("handleid") == null ? null : ((Number)row.get("handleid")).longValue();
            if (handleId == null) continue;
            java.util.LinkedHashMap<String, Object> handle = grouped.computeIfAbsent(handleId, k -> {
                java.util.LinkedHashMap<String, Object> h = new java.util.LinkedHashMap<>();
                for (String field : TASKHANDLE_FIELDS) {
                    if (row.containsKey(field)) h.put(field, row.get(field));
                }
                h.put("resources", new java.util.ArrayList<java.util.Map<String, Object>>());
                return h;
            });
            // 资源字段
            if (row.get("resourcesid") != null) {
                java.util.LinkedHashMap<String, Object> resource = new java.util.LinkedHashMap<>();
                for (String field : RESOURCE_FIELDS) {
                    if (row.containsKey(field)) resource.put(field, row.get(field));
                }
                ((java.util.List<java.util.Map<String, Object>>)handle.get("resources")).add(resource);
            }
        }
        // 对每个handle的resources按resourcesid升序排序
        for (java.util.LinkedHashMap<String, Object> handle : grouped.values()) {
            java.util.List<java.util.Map<String, Object>> resources = (java.util.List<java.util.Map<String, Object>>)handle.get("resources");
            resources.sort((a, b) -> {
                Long id1 = a.get("resourcesid") == null ? 0L : ((Number)a.get("resourcesid")).longValue();
                Long id2 = b.get("resourcesid") == null ? 0L : ((Number)b.get("resourcesid")).longValue();
                return id1.compareTo(id2);
            });
        }
        return Result.success(new ArrayList<>(grouped.values()));
    }

    private Map<String, Object> wrapHandleWithResource(Map<String, Object> map) {
        if (map == null) return null;
        java.util.LinkedHashMap<String, Object> result = new java.util.LinkedHashMap<>();
        java.util.LinkedHashMap<String, Object> resource = new java.util.LinkedHashMap<>();
        // 主表字段
        for (String field : TASKHANDLE_FIELDS) {
            if (map.containsKey(field)) result.put(field, map.get(field));
        }
        // 资源字段
        for (String field : RESOURCE_FIELDS) {
            if (map.containsKey(field)) resource.put(field, map.get(field));
        }
        // 其他字段补充
        for (String key : map.keySet()) {
            if (!result.containsKey(key) && !resource.containsKey(key)) {
                result.put(key, map.get(key));
            }
        }
        if (!resource.isEmpty() && resource.get("resourcesid") != null) result.put("resource", resource);
        return result;
    }

    @GetMapping("/withResource/handle/{handleId}")
    public Result<Map<String, Object>> getWithResourceByHandleId(@PathVariable Long handleId) {
        List<Map<String, Object>> flatList = taskHandleService.getHandleWithResourcesByHandleId(handleId);
        if (flatList.isEmpty()) return Result.success(null);
        Map<String, Object> first = flatList.get(0);
        java.util.LinkedHashMap<String, Object> handle = new java.util.LinkedHashMap<>();
        for (String field : TASKHANDLE_FIELDS) {
            if (first.containsKey(field)) handle.put(field, first.get(field));
        }
        java.util.List<java.util.Map<String, Object>> resources = new java.util.ArrayList<>();
        for (Map<String, Object> row : flatList) {
            if (row.get("resourcesid") != null) {
                java.util.LinkedHashMap<String, Object> resource = new java.util.LinkedHashMap<>();
                for (String field : RESOURCE_FIELDS) {
                    if (row.containsKey(field)) resource.put(field, row.get(field));
                }
                resources.add(resource);
            }
        }
        resources.sort((a, b) -> {
            Long id1 = a.get("resourcesid") == null ? 0L : ((Number)a.get("resourcesid")).longValue();
            Long id2 = b.get("resourcesid") == null ? 0L : ((Number)b.get("resourcesid")).longValue();
            return id1.compareTo(id2);
        });
        handle.put("resources", resources);
        return Result.success(handle);
    }

    @GetMapping("/withResource/task/{taskId}")
    public Result<List<Map<String, Object>>> getWithResourceByTaskId(@PathVariable Long taskId) {
        List<Map<String, Object>> flatList = taskHandleService.getHandleWithResourcesByTaskId(taskId);
        java.util.Map<Long, java.util.LinkedHashMap<String, Object>> grouped = new java.util.LinkedHashMap<>();
        for (Map<String, Object> row : flatList) {
            Long handleId = row.get("handleid") == null ? null : ((Number)row.get("handleid")).longValue();
            if (handleId == null) continue;
            java.util.LinkedHashMap<String, Object> handle = grouped.computeIfAbsent(handleId, k -> {
                java.util.LinkedHashMap<String, Object> h = new java.util.LinkedHashMap<>();
                for (String field : TASKHANDLE_FIELDS) {
                    if (row.containsKey(field)) h.put(field, row.get(field));
                }
                h.put("resources", new java.util.ArrayList<java.util.Map<String, Object>>());
                return h;
            });
            // 资源字段
            if (row.get("resourcesid") != null) {
                java.util.LinkedHashMap<String, Object> resource = new java.util.LinkedHashMap<>();
                for (String field : RESOURCE_FIELDS) {
                    if (row.containsKey(field)) resource.put(field, row.get(field));
                }
                ((java.util.List<java.util.Map<String, Object>>)handle.get("resources")).add(resource);
            }
        }
        // 对每个handle的resources按resourcesid升序排序
        for (java.util.LinkedHashMap<String, Object> handle : grouped.values()) {
            java.util.List<java.util.Map<String, Object>> resources = (java.util.List<java.util.Map<String, Object>>)handle.get("resources");
            resources.sort((a, b) -> {
                Long id1 = a.get("resourcesid") == null ? 0L : ((Number)a.get("resourcesid")).longValue();
                Long id2 = b.get("resourcesid") == null ? 0L : ((Number)b.get("resourcesid")).longValue();
                return id1.compareTo(id2);
            });
        }
        return Result.success(new java.util.ArrayList<>(grouped.values()));
    }
} 